<script setup>
import {
  onMounted,
  ref,
  reactive,
  toRefs,
  getCurrentInstance,
  computed,
  watch,
  toRaw,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import utils from "@/utils/utils";
import QueryForm from "../../../packages/QueryForm/QueryForm.vue";

import BaseTable from "../../../packages/BaseTable/BaseTable.vue";

// getCurrentInstance方法只能在setup函数中使用，想要获取到上下文并获得全局挂载方法需要使用proxy属性进行调用
const { proxy } = getCurrentInstance();
const data = reactive({
  user: { status: "" },
  columns: [],
  userList: [],
  sellerData: { status: 0, resellerName: "" },
});
// 初始化分页对象
const pager = reactive({
  pageNum: 1,
  pageSize: 10,
});
// 定义输入自定义组件的参数 -- 相当于用户输入的自定义json
const form = [
  {
    type: "input",
    label: "经销商名称",
    model: "dealerName",
    placeholder: "请输入经销商名称",
  },
  {
    type: "select",
    label: "状态",
    model: "status",
    placeholder: "请选择状态",
    options: [
      {
        label: "全部",
        value: "",
      },
      {
        label: "启用",
        value: 0,
      },
      {
        label: "禁用",
        value: 1,
      },
    ],
  },
  {
    type: "input",
    label: "用户名",
    model: "userName",
    placeholder: "请输入用户名",
  },
];
// 动态表格格式
data.columns = [
  {
    type: "selection",
  },
  {
    label: "序号",
    prop: "dealerId",
  },
  {
    label: "经销商名称",
    prop: "dealerName",
  },
  {
    label: "用户名",
    prop: "userName",
  },
  {
    label: "联系人",
    prop: "contact",
  },
  {
    label: "电子邮箱",
    prop: "email",
  },
  {
    label: "手机号码",
    prop: "phonenumber",
  },
  {
    label: "状态",
    prop: "status",
    formatter(row, column, value) {
      return {
        0: "启用",
        1: "禁用",
      }[value];
    },
  },
  {
    label: "创建人",
    prop: "createBy",
  },
  {
    label: "注册时间",
    prop: "createTime",
    width: 180,
    // 时间格式化
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "修改人",
    prop: "updateBy",
  },
  {
    label: "修改时间",
    prop: "updateTime",
    width: 180,
    // 时间格式化
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "备注",
    prop: "remark",
  },
  {
    label: "操作",
    type: "action",
    width: 360,
    list: [
      {
        text: "删除",
        type: "danger",
      },
      {
        text: "重置密码",
        type: "warning",
      },
      {
        text: "编辑",
        type: "primary",
      },
      {
        text: "关联查询",
        type: "",
      },
    ],
  },
];
// 弹框显示
let showModel = ref(false);
// 新增用户
const userForm = reactive({});
// 定义表单校验规则
const rules = reactive({
  userName: [
    {
      required: true,
      message: "请输入用户名称",
      trigger: "blur",
    },
  ],
  userEmail: [
    {
      required: true,
      message: "请输入用户邮箱",
      trigger: "blur",
    },
  ],
  deptId: [
    {
      required: true,
      message: "请输入用户职位",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /1\d{10}/,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
  ],
});
// 选中用户列表的对象
let checkedUserIds = ref([]);
// 用户创建行为
const action = ref("add");
// 分配角色弹框
const showSellerModals = ref(false);
// 点击的经销商ID
const dealerId = ref("");

// 获取用户账号列表
const getSellerAccountList = async () => {
  let params = {
    ...data.user,
    pageNum: pager.pageNum,
    pageSize: pager.pageSize,
  };
  try {
    const { list, pageNum, pageSize, total } =
      await proxy.$api.getSellerAccountList(params);
    data.userList = list;
    pager.total = total;
    pager.pageNum = pageNum;
    pager.pageSize = pageSize;
  } catch (err) {
    console.log(err);
  }
};

onMounted(() => {
  // 初始化获取经销商账号列表
  getSellerAccountList();
});
// 查询经销商账号
const handleQuery = () => {
  getSellerAccountList();
};
// 表格每一项后面action按钮对应的操作
const handleAction = ({ index, row }) => {
  if (index == 0) {
    // 删除
    handleDel(row);
  } else if (index == 1) {
    // 重置密码
    resetSellerAccountPassword(row);
  } else if (index == 2) {
    // 编辑
    handleEdit(row);
  } else if (index == 3) {
    // 经销商关联查询
    handleSellerQuery(row);
  }
};
// 重置查询表单
const handleReset = (form) => {
  proxy.$refs?.[form].resetFields();
};
// 重置密码
const resetSellerAccountPassword = async (row) => {
  ElMessageBox.alert("确认重置密码吗？", "重置密码", {
    confirmButtonText: "OK",
    callback: async (action) => {
      if (action === "cancel") return;
      try {
        await proxy.$api.resetSellerAccountPassword({
          dealerId: row.dealerId,
        });
        proxy.$message.success("重置密码成功！");
      } catch (error) {
        proxy.$message.error(`重置密码失败，请稍后再试：${error.message}`);
      }
    },
  });
};
// 切换页号
const handleCurrentChange = (current) => {
  pager.pageNum = current;
  getSellerAccountList();
};
// 禁用
const handleDisabled = async () => {
  if (checkedUserIds.value.length == 0) {
    proxy.$message.error("请选择要禁用的用户");
    return;
  }
  try {
    await proxy.$api.changeSellerAccountStatus({
      dealerIds: [...toRaw(checkedUserIds.value)],
      status: 1,
    });
    proxy.$message.success("账户禁用成功！");
  } catch (error) {
    proxy.$message.error(`账户禁用失败，请稍后再试：${error.message}`);
  }
  // 启用禁用后重新查询列表
  getSellerAccountList();
};
// 启用
const handleEnabled = async () => {
  if (checkedUserIds.value.length == 0) {
    proxy.$message.error("请选择要启用的用户");
    return;
  }
  try {
    await proxy.$api.changeSellerAccountStatus({
      dealerIds: [...toRaw(checkedUserIds.value)],
      status: 0,
    });
    proxy.$message.success("账户启用成功！");
  } catch (error) {
    proxy.$message.error(`账户启用失败，请稍后再试：${error.message}`);
  }
  // 启用禁用后重新查询列表
  getSellerAccountList();
};
// 单一用户删除
const handleDel = async (row) => {
  try {
    await proxy.$api.deleteSellerAccount({
      dealerIds: [row.dealerId],
    });
    proxy.$message.success("删除成功");
    getSellerAccountList();
  } catch (error) {
    proxy.$message.error(`删除失败，请稍后再试: ${error}`);
  }
};
// 批量用户删除
const handlePatchDel = async () => {
  if (checkedUserIds.value.length == 0) {
    proxy.$message.error("请选择要删除的用户");
    return;
  }
  try {
    const res = await proxy.$api.deleteSellerAccount({
      dealerIds: checkedUserIds.value,
    });
    if (res) {
      proxy.$message.success("删除成功");
      getSellerAccountList();
    }
  } catch (error) {
    proxy.$message.error(`删除失败，请稍后再试: ${error}`);
  }
};
// 表格多选
const handleSelectionChange = (list) => {
  let arr = [];
  list.map((item) => {
    arr.push(item.dealerId);
  });
  checkedUserIds.value = arr;
};
// 用户新增
const handleCreate = () => {
  action.value = "add";
  showModel.value = true;
};
// 用户弹窗关闭
const handleClose = () => {
  showModel.value = false;
  handleReset("logoForm");
};
// 提交（新增/编辑账号信息）
const handleSubmit = () => {
  //提交前校验
  proxy.$refs.logoForm.validate(async (valid) => {
    if (valid) {
      // 将响应式对象转为普通对象
      let params = toRaw(userForm);
      // 新增 / 修改
      const res = await proxy.$api.submitSellerMessage(params, action.value);
      if (res) {
        showModel.value = false;
        proxy.$message.success(
          `${action.value === "add" ? "账号编辑成功" : "账号创建成功"}`
        );
        handleReset("logoForm");
        getSellerAccountList();
      }
    }
  });
};
// 用户信息编辑
const handleEdit = (row) => {
  action.value = "edit";
  showModel.value = true;

  // 在下一个生命周期执行
  proxy.$nextTick(() => {
    // 使用浅拷贝将值赋给userForm
    const obj = {
      ...row,
    };
    Object.assign(userForm, obj);
  });
};
// 经销商关联按钮
const handleSellerQuery = (row) => {
  showSellerModals.value = true;
  relieveSellerList.value = row.resellers;
  dealerId.value = row.dealerId;

  handleSellerListQuery();
};

const { user, columns, userList, sellerData } = toRefs(data);

//经销商列表初始化查询
const handleSellerListQuery = async () => {
  try {
    const { list, pageNum, pageSize, total } = await proxy.$api.sellerList({
      ...sellerPager,
      ...data.sellerData,
    });

    sellerList.value = list;
    sellerPager.total = total;
    sellerPager.pageNum = pageNum;
    sellerPager.pageSize = pageSize;

    const showSellerList = () => {
      const resellerIds = relieveSellerList.value.map((item) => {
        return item.resellerId;
      });
      return sellerList.value.map((item) => {
        const ele = toRaw(item);
        if (resellerIds.includes(ele.resellerId)) {
          toRaw(item).disabled = true;
        } else {
          toRaw(item).disabled = false;
        }

        return item;
      });
    };
    sellerList.value = showSellerList();
  } catch (error) {
    alert("经销商查询失败");
  }
};

const sellerColumns = [
  {
    label: "序号",
    prop: "resellerId",
  },
  {
    label: "经销商名称",
    prop: "resellerName",
  },
  {
    label: "经销商简称",
    prop: "abbrName",
  },
  {
    label: "状态",
    prop: "status",
    formatter(row, column, value) {
      return {
        0: "启用",
        1: "禁用",
      }[value];
    },
  },
  {
    label: "注册时间",
    prop: "createTime",
    width: 180,
    // 时间格式化
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "修改时间",
    prop: "updateTime",
    width: 180,
    // 时间格式化
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "操作",
    type: "action",
    width: 180,
    list: [
      {
        text: "解除关联",
        type: "danger",
      },
    ],
  },
];
// 关联经销商列表
const relieveSellerList = ref([]);
// 关联经销商
const handleSellerAction = (index, row) => {
  try {
    const res = proxy.$api.relieveSellerRelevancy({
      resellerId: row.resellerId,
      dealerId: dealerId.value,
    });
    if (res) {
      proxy.$message.success("解除关联成功！");
      showSellerModals.value = false;
      getSellerAccountList();
    }
  } catch (error) {
    proxy.$message.error(`解除关联失败，请稍后再试：${error}`);
  }
};

const sellerListColumns = [
  {
    label: "序号",
    prop: "resellerId",
  },
  {
    label: "经销商名称",
    prop: "resellerName",
  },
  {
    label: "经销商简称",
    prop: "abbrName",
  },
  {
    label: "状态",
    prop: "status",
    formatter(row, column, value) {
      return {
        0: "启用",
        1: "禁用",
      }[value];
    },
  },
  {
    label: "注册时间",
    prop: "createTime",
    width: 180,
    // 时间格式化
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "修改时间",
    prop: "updateTime",
    width: 180,
    // 时间格式化
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "操作",
    type: "action",
    width: 180,
    list: [
      {
        text: "关联",
        type: "primary",
      },
    ],
  },
];
const sellerForm = [
  {
    type: "input",
    label: "经销商名称",
    model: "resellerName",
    placeholder: "请输入经销商名称",
  },
  {
    type: "select",
    label: "经销商状态",
    model: "status",
    placeholder: "请选择经销商状态",
    options: [
      {
        label: "全部",
        value: "",
      },
      {
        label: "启用",
        value: 0,
      },
      {
        label: "禁用",
        value: 1,
      },
    ],
  },
];
// const sellerData = reactive({ status: 0, resellerName: "" });
// 经销商列表分页器
const sellerPager = reactive({
  pageNum: 1,
  pageSize: 4,
});
// 经销商列表
const sellerList = ref([]);
// 关联操作
const handleRelieveSellerAction = async ({ index, row }) => {
  try {
    const res = await proxy.$api.sellerRelevancy({
      dealerId: dealerId.value,
      resellerId: row.resellerId,
    });
    if (res) {
      proxy.$message.success("关联成功");
      showSellerModals.value = false;
      getSellerAccountList();
    }
  } catch (error) {
    proxy.$message.error("关联失败");
  }
};
</script>

<template>
  <div class="user-manage">
    <div class="query-form">
      <query-form
        :form="form"
        v-model="user"
        @handleQuery="handleQuery"
      ></query-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleCreate">新增</el-button>
        <el-button type="danger" @click="handlePatchDel">删除</el-button>
        <el-button type="info" @click="handleDisabled">禁用</el-button>
        <el-button type="success" @click="handleEnabled">启用</el-button>
      </div>
      <base-table
        :pager="pager"
        :columns="columns"
        :data="userList"
        @selection-change="handleSelectionChange"
        @handleAction="handleAction"
        @handleCurrentChange="handleCurrentChange"
      >
        <template v-slot="action">
          <el-button type="primary" @click="handleCreate" v-has="'user-create'"
            >新增</el-button
          >
          <el-button
            type="danger"
            @click="handlePatchDel"
            v-has="'user-patch-delete'"
            >批量删除</el-button
          >
        </template>
      </base-table>
    </div>
    <el-dialog
      :title="action === 'add' ? '新增账号' : '修改账户信息'"
      v-model="showModel"
    >
      <el-form
        ref="logoForm"
        :model="userForm"
        label-width="100"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="经销商名称" prop="dealerName">
          <el-input
            v-model="userForm.dealerName"
            placeholder="请输入真实姓名"
          />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="userForm.contact" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="userForm.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入电子邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="userForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="已关联经销商" v-model="showSellerModals">
      <div style="margin-bottom: 30px">
        <el-table :data="relieveSellerList" stripe style="width: 100%">
          <template v-for="item in sellerColumns" :key="item.prop">
            <el-table-column
              type="selection"
              width="55"
              v-if="item.type == 'selection'"
              key="selection"
            ></el-table-column>
            <el-table-column v-else-if="!item.type" v-bind="item">
            </el-table-column>
            <el-table-column v-if="item.type == 'action'" v-bind="item">
              <!-- 自定义插槽获取当前行值 -->
              <template #default="scope">
                <template v-for="(btn, index) in item.list">
                  <el-button
                    :type="btn.type"
                    @click="handleSellerAction(index, scope.row)"
                    >{{ btn.text }}</el-button
                  >
                </template>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div>
        <div class="query-form">
          <query-form
            :form="sellerForm"
            v-model="sellerData"
            @handleQuery="handleSellerListQuery"
          ></query-form>
        </div>
        <base-table
          :pager="sellerPager"
          :columns="sellerListColumns"
          :data="sellerList"
          @handleAction="handleRelieveSellerAction"
          @handleCurrentChange="handleCurrentChange"
        >
        </base-table>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.user-manage {
  height: 100%;
  overflow-y: scroll;
}

.query-form {
  display: flex;
  align-items: center;
  background: #fff;
  padding-top: 18px;
  margin-bottom: 16px;
  padding-left: 20px;
  border-radius: 4px;
}

.base-table {
  background: #fff;
  border-radius: 4px;

  .action {
    padding: 15px;
    border-bottom: 1px solid #eee;
  }
}

.pagination {
  justify-content: flex-end;
  padding: 8px 20px;
}
</style>
